<?php
//require_once 'dr-app-config.php';
//echo '<pre>';
/**
 * 获取用户的个人信息
 */
function dr_db_get_user_profile($user_id)
{
	global $db;

	# 获得用户的信息
	$u_sql = 'select username, email, nickname, last_login_date, registered_date,
		status, level, points from ^users where user_id=$';
	$u_result = dr_db_query_sub($db, $u_sql, $user_id);

	$u_array_result = mysql_fetch_assoc($u_result);

	# 获得用户的meta信息
	$um_sql = 'select meta_key, meta_value from ^usermeta where user_id=$';
	$um_result = dr_db_query_sub($db, $um_sql, $user_id);

	$um_array_result = array();
	while ($row = mysql_fetch_assoc($um_result)) {
		$um_array_result[$row['meta_key']] = $row['meta_value'];
	}

	# 合并获得数据
	$result = array_merge($u_array_result, $um_array_result);

	# 返回用户的数据
	return $result;
}

//var_dump( dr_db_get_user_profile(2) );

/**
 * 获得用户编辑个人信息的时候的个人数据
 *
 * @param unknown_type $user_id
 */
function dr_db_get_user_profile_for_edit($user_id)
{
	global $db;

	# 获得用户的信息
	$u_sql = 'select username, nickname, email from ^users where user_id=$';
	$u_result = dr_db_query_sub($db, $u_sql, $user_id);

	$u_array_result = mysql_fetch_assoc($u_result);

	# 获得用户的meta信息
	$um_sql = 'select meta_key, meta_value from ^usermeta where user_id=$';
	$um_result = dr_db_query_sub($db, $um_sql, $user_id);

	$um_array_result = array();
	while ($row = mysql_fetch_assoc($um_result)) {
		$um_array_result[$row['meta_key']] = $row['meta_value'];
	}

	# 合并获得数据
	$result = array_merge($u_array_result, $um_array_result);

	# 返回用户的数据
	return $result;
}

function dr_db_set_user_profile_after_edit($user_id, $profile)
{
	global $db;

	$u_sql = 'update ^users set nickname=$ where user_id=$';
	$u_result = dr_db_query_sub($db, $u_sql, $profile['nickname'], $user_id);
	if (!$u_result) return false;

	unset($profile['nickanme']);
	unset($profile['username']);
	unset($profile['email']);

	$old_profile = dr_get_user_profile_for_edit($user_id);
	$old_keys = array_keys($old_profile);

	$um_sql_update = "UPDATE `^usermeta` SET `meta_value` = $ WHERE `meta_key` = $ AND `user_id` = $";
	$um_sql_insert = "INSERT INTO `^usermeta` (`user_id`, `meta_key`, `meta_value`) values ($, $, $)";
	foreach ($profile as $key => $value) {
		if (!in_array($key, $old_keys)) {
			dr_db_query_sub($db, $um_sql_insert, $user_id, $key, $value);
		}
		dr_db_query_sub($db, $um_sql_update, $value, $key, $user_id);
	}

	return true;
}

//dr_db_set_user_profile_after_edit(1, array('nickname'=>'hutushen222'));

